package com.example.java_chatroom_redis_rabbitmq.controller;

import com.example.java_chatroom_redis_rabbitmq.model.Friend;
import com.example.java_chatroom_redis_rabbitmq.model.Result;
import com.example.java_chatroom_redis_rabbitmq.model.User;
import com.example.java_chatroom_redis_rabbitmq.service.FriendService;
import com.example.java_chatroom_redis_rabbitmq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RequestMapping("/friend")
@RestController
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private UserService userService;

    @RequestMapping("/getFriendList")
    public Result<List<Friend>> getFriendList(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        List<Integer> friendList = friendService.getFriendIdByUserId(user.getUserId());
        if (friendList == null || friendList.size() == 0) {
            return Result.success(null);
        }
        List<Friend> ret = new ArrayList<>();
        for (int n : friendList) {
            User friend = userService.queryUserByUserId(n);
            Friend friend1 = new Friend();
            friend1.setFriendId(n);
            friend1.setFriendName(friend.getUserName());
            friend1.setFriendImage(friend.getImage());
            ret.add(friend1);
        }
        Collections.sort(ret, new Comparator<Friend>() {
            @Override
            public int compare(Friend o1, Friend o2) {
                return o1.getFriendName().compareTo(o2.getFriendName());
            }
        });
        return Result.success(ret);
    }

}
